const fs = require('fs')
const path = require('path')
const multer = require('@koa/multer');
const uploaderRoot = CONFIG.server.uploads
if (!fs.existsSync(uploaderRoot)) {
  fs.mkdirSync(uploaderRoot)
}

// // 检查图片格式是否合法
// function checkIsImg(fields={}){
//   let filterPicture = ['.jpg','.jpeg','.png','.gif', 'pdf']
//   if (fields.name) {
//     let ext = path.extname(fields.name)
//     if (filterPicture.indexOf(ext)>-1) {
//       return true
//     }
//   }
// }

// // 保存图片至本地
// // async-busboy版本，使用busboy
// async function up2local(ctx, next){
//   const {files, fields} = await asyncBusboy(ctx.req);  // async-busboy
//   if (checkIsImg(fields)) {
//     let filename = `${Date.now().toString(16)}-${fields.name}`
//     let filepath = path.join(uploaderRoot, filename)
//     let stream = fs.createWriteStream(filepath)
//     stream.on('close', function(){
//       ctx.body = {
//         code: '00',
//         data: {
//           filename: filename
//         }
//       }
//     })
//     files[0].pipe(stream)
//   }
// }


// ============ multer ??? ============

//上传文件存放路径、及文件命名
let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploaderRoot)
  },
  filename: function (req, file, cb) {
    let type = file.originalname.split('.')[1]
    cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
  }
})

let defaultLimits = {
  fields: 10, //非文件字段的数量
  fileSize: 500 * 1024, //文件大小 单位 b
}

function getUpload(lmt={}){
  let limits = Object.assign({}, defaultLimits, lmt)
  return multer({storage, limits})
}

async function up2localSingle(ctx, next){
  const upload = getUpload({files: 1})
  await upload.single('file')(ctx, next)
  console.log(ctx.request.file);
  const file = ctx.request.file
  const result = {
    filename: file.filename,
    mimetype: file.mimetype,
    originalname: file.originalname
  }
  ctx.body = result
}



export default function(aks){
  aks.routepreset('/uploader', {
    customControl: up2localSingle
  })
}
